import { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
type EChartsOption = echarts.EChartsOption
type Data = { value: number; name: string }
type Props = {
  chartOption: {
    name: string
    data: Data[]
    size: { width: number; height: number }
  }
}

function Pie({ chartOption }: Props) {
  const pieRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const chartInit = () => {
      let myChart = echarts.init(pieRef.current!)
      const option: EChartsOption = {
        tooltip: {
          trigger: 'item',
        },
        legend: {
          top: '5%',
          left: 'center',
        },
        series: [
          {
            name: chartOption.name,
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2,
            },
            label: {
              show: false,
              position: 'center',
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '40',
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
            data: chartOption.data,
          },
        ],
      }
      option && myChart.setOption(option)
    }
    chartInit()
  }, [chartOption])
  return <div ref={pieRef} style={chartOption.size}></div>
}

export default Pie
